<?php
declare (strict_types = 1);

namespace app\mini\controller;

use app\admin\model\Setting;
use app\admin\model\Slideshow;
use app\crm\model\ShortMessageTplModel;
use app\mini\model\CustomerPointGoodsBuy;
use app\mini\model\CustomerPointLogModel;
use app\mini\model\CustomerPointModel;
use app\mini\model\CustomerSign;
use app\mini\model\MiniPrizeLog;
use think\response\Json;
use app\mini\model\SysModelMiniCustomer;
use app\crm\model\Customer as CustomerModel;
use app\mini\model\PersonCustomer;
use app\crm\model\Setting as SettingModel;
use app\mini\model\PersonCase as PersonCaseModel;
use app\crm\model\ReturnVist;
use app\admin\model\File as FileModel;
use app\mini\model\AddModel;

use think\facade\Db;
/**
 * Class Index
 * @package app\mini\controller
 * @author Mr.Liu Wuchen
 * @create 2021-07-02 10:42
 */
class IndexCustomer extends Access
{
    /**
     * 客户小程序新增服务评价接口
     * @return Json
     * @author yp
     */
    public function addEvaluation():Json
    {
        $request = $this->request->param();

        $model = new SysModelMiniCustomer();

        $data = $model->addEvaluation($request);

        return resultArray(['error' => '评价成功', 'data' => $data]);
    }

    /**
     * 获取当前月份日期
     * @return Json
     * @author YP
     */
    public function getMonthDays():Json
    {
        $time = time();
        $year = date('Y',$time);
        $month = date('m',$time);
        $t = date('t',$time)+7;

        $timeStr = strtotime($year.'-'.$month.'-'.'01');

        $date = [];

        for($i=0;$i<$t;$i++){

            $timeS = $timeStr+86400*$i;

            $days = date('m-d',$timeS);

            // $days = '';

            // $days = $month.'-'.$i;

            array_push($date,$days);

        }

        // echo "<pre>";
        // print_r($date);
        // echo "</pre>";
        // exit;

        return resultArray(['error' => '获取成功', 'data' => $date]);
    }

    /**
     * 获取员工当月排班列表
     * @return Json
     * @author YP
     */
    public function scheduleList(): Json
    {

        $request = $this->request->param();

        $model = new SysModelMiniCustomer();

        $data = $model->getScheduleList($request);

        return resultArray(['error' => '获取成功', 'data' => $data]);

    }

    /**
     * 设置员工排班
     * @return Json
     * @author YP
     */
    public function setSchedule()
    {
        $request = $this->request->param();

        $model = new SysModelMiniCustomer();

        $data = $model->setSchedule($request);

        if (!$data) {

            return resultArray(['error' => $model->error]);

        }

        return resultArray(['data' => $data,'msg' =>"编辑完成"]);
    }


    /**
     * 客户小程序获取门店信息
     * @return Json
     * @author YP
     */
    public function getShopInfo(): Json
    {
        $request = $this->request->param();

        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;

        $model = new SysModelMiniCustomer();

        $data = $model->getShopInfo($request);

        return resultArray(['error' => '获取成功', 'data' => $data]);
    }

    /**
     * 获取可预约日期
     * @return Json
     * @author YP
     */
    public function bookDate(): Json
    {

        $request = $this->request->param();

        $model = new SysModelMiniCustomer();

        $data = $model->bookDate($request);

        return resultArray(['error' => '获取成功', 'data' => $data]);

    }

    /**
     * 获取规定日期可预约的时间段
     * @return Json
     * @author YP
     */
    public function bookTime(): Json
    {
        // $request = $this->request->param();

        // $model = new SysModelMiniCustomer();

        // $data = $model->bookTime($request);

        return resultArray(['error' => '请重新加载小程序！', 'data' => []]);
    }

    /**
     * 获取规定日期可预约的时间段
     * @return Json
     * @author YP
     */
    public function bookTime2(): Json
    {
        $request = $this->request->param();

        $model = new SysModelMiniCustomer();

        $data = $model->bookTime2($request);

        return resultArray(['error' => '获取成功', 'data' => $data]);
    }

    /**
     * 获取可预约护理师列表
     * @return Json
     * @author YP
     * 参数：预约日期，预约时间，预约门店
     */
    public function getYYStaff(): Json
    {
        $request = $this->request->param();

        $model = new SysModelMiniCustomer();

        $data = $model->getYYStaff($request);

        return resultArray(['error' => '获取成功', 'data' => $data]);
    }


    /**
     * 提交预约信息
     * @return Json
     * @author YP
     * 参数：预约日期，预约时间，预约门店
     */
    public function submitYYInfo(): Json
    {

        $request = $this->request->param();

        $model = new SysModelMiniCustomer();

        // $request['msg'] = '预约参数';

        $data = $model->addYYData($request);

        return resultArray(['error' => '获取成功', 'data' => $data]);

    }

    /**
     * 提交预约信息
     * @return Json
     * @author YP
     * 参数：预约日期，预约时间，预约门店
     */
    public function submitYYInfo2(): Json
    {

        $request = $this->request->param();

        $model = new SysModelMiniCustomer();

        // $request['msg'] = '预约参数';

        $data = $model->addYYData2($request,$this->app);

        return resultArray(['error' => '获取成功', 'data' => $data]);

    }

    /**
     * 客户小程序获取预约列表
     * @return Json
     * @author YP
     * 参数：
     */
    public function getBookList(): Json
    {

        $request = $this->request->param();

        $model = new SysModelMiniCustomer();

        $data = $model->getBookList($request);

        return resultArray(['error' => '获取成功', 'data' => $data]);

    }

    /**
     *  客户小程序满意度调查客户结果提接口
     *  @return Json
     */
    public function addQuestionCustomer(): Json
    {
        $request = $this->request->param();

        $model = new SysModelMiniCustomer();

        $data = $model->addQuestionCustomer($request);

        return resultArray(['error' => '获取成功', 'data' => $data]);
    }

    /**
     *  取消预约信息
     *  @return Json
     */
    public function cancelBook(): Json
    {

        $request = $this->request->param();

        $model = new SysModelMiniCustomer();

        $data = $model->cancelBook($request,$this->app);

        return resultArray(['error' => '操作成功', 'data' => $data]);


    }

    /**
     * getSetting category_id = 14
     * @return Json
     */
    public function getSetting14(): Json
    {
        $request = $this->request->param();

        $model = new SysModelMiniCustomer();

        $data = $model->getSetting14($request);

        return resultArray(['error' => '获取成功', 'data' => $data]);
    }

    /**
     * 新增意见反馈
     */
    public function addFeedback(): Json
    {
        $request = $this->request->param();

        $model = new AddModel();

        $data = $model->addFeedback($request);

        return resultArray(['error' => '新增成功', 'data' => $data]);
    }

    /**
     * 一次性设置一周排班
     */
    public function setScheduleWeek(): Json
    {
        $request = $this->request->param();

        $model = new SysModelMiniCustomer();

        $data = $model->setScheduleWeek($request);

        if (!$data) {

            return resultArray(['error' => $model->error]);

        }

        return resultArray(['data' => $data,'msg' =>"编辑完成"]);
    }

    /**
     * 判断是否为本月第一次评价
     *
     * @return int
     */
    public function isFirst()
    {
        $request = $this->request->param();
        $where = [];
        $date = strtotime((date("Y-m",time())));
        array_push($where,['customer_id','=',$request['id']]);
        array_push($where,['create_time','>=',$date]);
        $evaluation = Db::name('service_log_evaluation')->where($where)->count();
        if($evaluation)
        {
            return 1 ;
        }else{
            return 0;
        }
    }

    /**
     * 转介绍结果
     * @return Json
     */
    public function turnList()
    {
        $request = $this->request->param();
        $customerId = $request['id'];
        $result = CustomerModel::where('turn_id', '=', $customerId)->select()->column('customer_name,telephone');
        $total = CustomerModel::where('turn_id', '=', $customerId)->count();
        return $this->success($result, '获取完成', $total);

    }
    /**
     * 客户签到
     *
     * @return \think\response\Json
     */
    public function sign()
    {
        $param = request()->param();
        $customerId = $param['customer_id'];
        $time = time();
        $start_time=strtotime("last Monday",$time);
        $w = date('w',$time);
        if($w == 0)
        {
            $w = 7;
        }
        if($w == 1||$w == 0)
        {
            $start_time += 7*24*60*60;
        }
        $w--;
        $end_time = $start_time + 7*24*60*60 -1;
        $signModel = CustomerSign::where([
            ['customer_id','=',$customerId],
            ['start_time','=',$start_time],
            ['end_time','=',$end_time]
        ])->find();
        if($signModel)
        {
            $signModel->sign=substr_replace($signModel->sign,'1',$w,1);
            $res=$signModel->save();
            if($signModel->sign == "1111111")
            {
                CustomerPointModel::pointChange($customerId,2);
            }
        }else{
            $signModel = new CustomerSign();
            $sign = "00000000";
            $sign=substr_replace($sign,'1',$w,1);
            $signModel->sign = $sign;
            $signModel->customer_id = $customerId;
            $signModel->start_time = $start_time;
            $signModel->end_time = $end_time;
            $res=$signModel->save();
        }
        CustomerPointModel::pointChange($customerId,1);
        if($res)
        {
            return $this->success([], '签到成功');
        }else{
            return $this->failed(400, "签到失败");
        }
    }

    /**
     * 签到情况
     *
     * @return Json
     */
    public function signList()
    {
        $param = request()->param();
        $customerId = $param['customer_id'];
        $time = time();
        $w = date('w',$time)-1 == '-1' ? '6' : date('w',$time)-1;
        $where = [];
        array_push($where,['customer_id','=',$customerId]);
        array_push($where,['start_time','<=',$time]);
        array_push($where,['end_time','>=',$time]);
        $signModel = CustomerSign::where($where)->find();
        if(empty($signModel))
        {
            $signStr = "0000000";
        }else{
            $signStr = $signModel->sign;
        }
        $sign = str_split($signStr);

        // echo "<pre>";
        // print_r($sign);
        // echo "</pre>";
        // exit;

        foreach ($sign as $key =>$value)
        {
            if($key<=$w&&$value==1)
            {
                $sign[$key]=0;//已签
            }
            if($key<$w&&$value==0)
            {
                $sign[$key]=1;//未签
            }
            if($key==$w&&$value==0)
            {
                $sign[$key]=2;//可签
            }
            if($key>$w)
            {
                $sign[$key]=3;//未来可签
            }
        }
//        if($signStr == "1111110"||$signStr == "1111111")
//        {
//            $sign[6]=4;//签满一周
//        }

        if($sign[$w] == 0 || $sign[$w] == 4)
        {
            $isSign = 1;//当天已签
        }else{
            $isSign = 0;//当天未签
        }

        return $this->success([
            'sign'=>$sign,
            'is_sign'=>$isSign
        ], '获取成功');


    }
    /**
     * 小程序获取个人积分总值
     *
     * @return Json
     */
    public function getPersonPointMini()
    {
        $param = request()->param();
        $id = $param['id'];
        $customerPoint = CustomerPointModel::where('customer_id','=',$id)->find();
        $data['total'] = $customerPoint->total??0;
        return $this->success($data, '获取成功');
    }

    /**
     * 获取转介绍成功列表
     *
     * @return Json
     */
    public function getTurnPointLog()
    {
        $param = request()->param();
        $id = $param['id'];
        $where = [];
        array_push($where,['a.turn_id','=',$id]);
        array_push($where,['b.origin_id','=',11]);

        $log = Db::name('customer')->alias('a')
            ->join('customer_point_log b','a.id = b.customer_id')
            ->where($where)->column('a.customer_name,b.created_at');
        return $this->success($log, '获取成功');
    }


    // 获取市场门店列表
    public function getShopIds()
    {
        $param = request()->param();

        // echo '<pre>';
        // print_r($param);
        // echo "</pre>";
        // exit;

        $model = new SysModelMiniCustomer();
        $data = $model->getShopIds($param);
        return resultArray(['error' => '获取成功', 'data' => $data]);
    }
    public function receiveShortMessageCheckStatus()
    {
        $param = request()->param();
        $status = 0;
        if($param['check_status']=="SUCCESS")
        {
            $status=1;
        }
        if($param['check_status']=="FAIL")
        {
            $status=2;
        }
        if(!empty($status))
        {
            Db::name('short_message_tpl')->where('tpl_id','=',$param['tpl_id'])->update([
                'status'=>$status,
                'reason'=>$param['reason']
            ]);
        }
    }

    /**
     * 抽奖奖池列表
     *
     * @return Json
     */
    public function getPrizeList()
    {
        $param = request()->param();
        if(empty($param['event_id']))
        {
            return $this->failed(100, '活动id为必传字段');
        }
        $where = [];
        array_push($where,['event_id','=',$param['event_id']]);
        array_push($where,['status','=',1]);
        $prize = Db::name('mini_prize')->where($where)->order('position','asc')->select()->toArray();
        if(count($prize)>8||count($prize)<=0)
        {
            return $this->failed(100, '数据异常');

        }
        return $this->success($prize, '获取成功');
    }

    /**
     * 获取抽奖结果
     *
     * @return Json
     */
    public function getPrizeResult()
    {
        $param = request()->param();
        if(empty($param['customer_id']))
        {
            return $this->failed(100, '顾客id为必传字段');
        }
        $where = [];
        if(empty($param['event_id']))
        {
            return $this->failed(100, '活动id为必传字段');
        }
        $event = Db::name('mini_prize_event')->where([
            ['id','=',$param['event_id']],
            ['status','=',1]
        ])->find();
        if(empty($event))
        {
            return $this->failed("活动不存在或已下架");
        }
        array_push($where,['event_id','=',$param['event_id']]);
        array_push($where,['status','=',1]);
        $prize = Db::name('mini_prize')->where($where)->order('position','asc')->column('probability','id');
        $result = $this->get_prize($prize);
        Db::startTrans();
        try {
            if($result != 0)
            {
                $prize = Db::name('mini_prize')->where('id','=',$result)->find();
                if(empty($prize))
                {
                    return $this->failed(100,"数据异常");
                }
                $customerPointGoodsBuy = new CustomerPointGoodsBuy();
                switch ($prize['type'])
                {
                    case 1:{
                        $customerPointGoodsBuy->save([
                            'point_goods_id'=>$prize['object'],
                            'customer_id'=>$param['customer_id'],
                            'status'=>1
                        ]);
                        break;
                    }
                    case 2:{
                        $customerPointGoodsBuy->save([
                            'point_goods_id'=>$prize['object'],
                            'customer_id'=>$param['customer_id'],
                            'status'=>1
                        ]);
                        break;
                    }
                    case 3:{
                        CustomerPointModel::pointChange($param['customer_id'],$prize['object']);
                        break;
                    }
                    default:{
                        return $this->failed(100,"数据异常");
                    }
                }
            }
            CustomerPointModel::pointChange($param['customer_id'],27);
            MiniPrizeLog::prizeLog($param['customer_id'],$result,$param['event_id']);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
        return $this->success(['result'=>$result], '获取成功');
    }

    /**
     * 抽奖结果计算
     *
     * @param $proArr
     * @return false|int|string
     */
    public function get_prize($proArr)
    {
        $result = '';
        $sum = 1000;//概率数组的总概率精度
        $proSum = array_sum($proArr);
        if ($proSum>$sum)
        {
            return false;
        }
        $proArr[0]=$sum-$proSum;
        $proSum = $sum;
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }

    public function getBannerList(): Json
    {
        $request = $this->request->param();

        $model = new SysModelMiniCustomer();

        $data = $model->getBannerList($request);

        return resultArray(['error' => '获取成功', 'data' => $data]);
    }

    public function skinType(): Json
    {
        //春 spring 中秋节 midAutumn
        return resultArray(['error' => '获取成功', 'data' => 'midAutumn']);
    }

    /**
     * 获取客户抽奖记录
     *
     * @return Json
     */
    public function getCustomerPrizeLog()
    {
        $request = $this->request->param();
        $where = [];
        array_push($where,['a.customer_id','=',$request['customer_id']]);
        array_push($where,['a.event_id','=',$request['event_id']]);

        $data = Db::name('mini_prize_log')->alias('a')
            ->field('b.name,a.created_at,a.prize_id')
            ->join('mini_prize b','a.prize_id = b.id','left')
            ->where($where)->order('a.created_at','desc')
            ->select()->toArray();
        foreach ($data as $key => $value)
        {
            $data[$key]['created_at']=date('Y-m-d H:i:s',$value['created_at']);
            if($value['prize_id'] == 0)
            {
                $data[$key]['name']="未中奖";
            }
        }
        return $this->success(['list'=>$data], '获取成功');
    }

    /**
     * 获取客户积分获取记录
     * 
     * @return Json
     */
    public function addPointLogs()
    {
        $request = $this->request->param();

        $model = new SysModelMiniCustomer();

        $data = $model->addPointLogs($request);

        return resultArray(['error' => '获取成功', 'data' => $data]);
    }

    /**
     * 获取客户积分消耗记录
     * 
     * @return Json
     */
    public function spendPointLogs()
    {
        $request = $this->request->param();

        $model = new SysModelMiniCustomer();

        $data = $model->spendPointLogs($request);

        return resultArray(['error' => '获取成功', 'data' => $data]);
    }

    /**
     * 获取服务评价问题列表
     */
    public function getQuestionList()
    {
        $request = $this->request->param();

        $questionId = 2;

        $questionList = Db::name('service_log_questions')->where('wenjuan',$questionId)->column('title,wenjuan,no');

        foreach ($questionList as $key => $value) {
            $questionList[$key]['is_checked'] = '';
            $questionList[$key]['score'] = '';
        }
        
        return resultArray(['error' => $questionId, 'data' => $questionList]);
    }

}

